<template>
  <div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Header -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900">车辆状态监测（热工况数据预处理）</h1>
            <p class="text-sm text-gray-500 mt-1">最后刷新：{{ lastRefreshTime }}</p>
          </div>
          <el-button
              type="primary"
              circle
              @click="showTechnicalModal = true"
          >
            <el-icon><QuestionFilled /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 视图模式切换 -->
      <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="flex items-center justify-between">
          <div class="flex space-x-2">
            <el-button
                :type="store.viewMode === 'list' ? 'primary' : 'default'"
                size="small"
                @click="store.setViewMode('list')"
            >
              列表视图
            </el-button>
            <el-button
                :type="store.viewMode === 'group' ? 'primary' : 'default'"
                size="small"
                @click="store.setViewMode('group')"
            >
              分组视图
            </el-button>
            <el-button
                :type="store.viewMode === 'compare' ? 'primary' : 'default'"
                size="small"
                @click="store.setViewMode('compare')"
            >
              对比模式
            </el-button>
            <el-button
                size="small"
                @click="showVehicleTable = true"
            >
              表格管理
            </el-button>
          </div>

          <div class="flex items-center space-x-4">
            <div v-if="store.viewMode === 'group'" class="flex items-center space-x-2">
              <span class="text-sm text-gray-600">分组方式:</span>
              <el-select v-model="store.groupBy" size="small" @change="store.setGroupBy">
                <el-option label="风险等级" value="riskLevel" />
                <el-option label="车型" value="model" />
                <el-option label="车队" value="fleet" />
              </el-select>
            </div>

            <div class="flex items-center space-x-2">
              <el-checkbox
                  :indeterminate="isIndeterminate"
                  v-model="checkAll"
                  @change="handleCheckAllChange"
              >
                全选
              </el-checkbox>
              <span class="text-sm text-gray-500">
                已选择 {{ store.selectedVehicleCount }} 辆
              </span>
            </div>

            <div class="flex space-x-2">
              <el-button
                  size="small"
                  :disabled="store.selectedVehicleCount === 0"
                  @click="batchAddToMonitor"
              >
                批量监控
              </el-button>
              <el-button
                  size="small"
                  :disabled="store.selectedVehicleCount === 0"
                  @click="batchExportData"
              >
                批量导出
              </el-button>
              <el-button
                  size="small"
                  :disabled="store.selectedVehicleCount < 2 || store.selectedVehicleCount > 4"
                  @click="showCompareModal = true"
              >
                对比分析
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 h-[calc(100vh-280px)]">
        <!-- Left Panel - Vehicle List -->
        <div class="lg:col-span-1 overflow-y-auto">
          <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex gap-4 mb-4">
              <el-select v-model="selectedRiskFilter" placeholder="筛选风险等级">
                <el-option label="全部" value="all" />
                <el-option label="高风险" value="high" />
                <el-option label="风险预警" value="warning" />
                <el-option label="低风险" value="low" />
              </el-select>
            </div>

            <!-- 列表视图 -->
            <div v-if="store.viewMode === 'list'" class="space-y-3">
              <div
                  v-for="vehicle in filteredVehicles"
                  :key="vehicle.id"
                  class="relative"
              >
                <el-checkbox
                    v-model="vehicle.selected"
                    @change="store.toggleVehicleSelection(vehicle.id)"
                    class="absolute top-2 left-2 z-10"
                />
                <VehicleCard
                    :vehicle="vehicle"
                    @select="selectVehicle"
                    class="ml-6"
                />
              </div>
            </div>

            <!-- 分组视图 -->
            <div v-else-if="store.viewMode === 'group'" class="space-y-4">
              <div
                  v-for="(vehicles, groupName) in store.groupedVehicles"
                  :key="groupName"
                  class="border rounded-lg p-3"
              >
                <div class="flex items-center justify-between mb-3">
                  <h4 class="font-medium text-gray-900">
                    {{ groupName }} ({{ vehicles.length }}辆)
                  </h4>
                  <el-button
                      size="small"
                      type="text"
                      @click="toggleGroupExpand(groupName)"
                  >
                    {{ expandedGroups.includes(groupName) ? '收起' : '展开' }}
                  </el-button>
                </div>
                <div
                    v-show="expandedGroups.includes(groupName)"
                    class="space-y-2"
                >
                  <div
                      v-for="vehicle in vehicles.filter(v => !selectedRiskFilter || selectedRiskFilter === 'all' || v.riskLevel === selectedRiskFilter)"
                      :key="vehicle.id"
                      class="relative"
                  >
                    <el-checkbox
                        v-model="vehicle.selected"
                        @change="store.toggleVehicleSelection(vehicle.id)"
                        class="absolute top-2 left-2 z-10"
                    />
                    <VehicleCard
                        :vehicle="vehicle"
                        @select="selectVehicle"
                        class="ml-6"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- 对比模式 -->
            <div v-else-if="store.viewMode === 'compare'" class="space-y-3">
              <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4">
                <div class="text-sm text-blue-800 mb-2">对比模式说明</div>
                <div class="text-xs text-blue-600">
                  选择2-4辆车辆进行热工况对比分析，已选择 {{ store.selectedVehicleCount }} 辆
                </div>
              </div>
              <div
                  v-for="vehicle in filteredVehicles"
                  :key="vehicle.id"
                  class="relative"
              >
                <el-checkbox
                    v-model="vehicle.selected"
                    @change="store.toggleVehicleSelection(vehicle.id)"
                    :disabled="!vehicle.selected && store.selectedVehicleCount >= 4"
                    class="absolute top-2 left-2 z-10"
                />
                <VehicleCard
                    :vehicle="vehicle"
                    @select="selectVehicle"
                    class="ml-6"
                    :class="{ 'ring-2 ring-blue-500': vehicle.selected }"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- Right Panel - Vehicle Details -->
        <div class="lg:col-span-2 overflow-y-auto">
          <div v-if="selectedVehicle" class="space-y-6">
            <!-- Basic Info -->
            <div class="bg-white rounded-lg shadow-sm p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-4">基础信息</h3>
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <span class="text-sm text-gray-500">车辆ID:</span>
                  <span class="font-medium ml-2">{{ selectedVehicle.id }}</span>
                </div>
                <div>
                  <span class="text-sm text-gray-500">车型:</span>
                  <span class="font-medium ml-2">{{ selectedVehicle.model }}</span>
                </div>
                <div class="col-span-2">
                  <span class="text-sm text-gray-500">数据采集周期:</span>
                  <span class="font-medium ml-2">每 5 分钟采集一次状态参数</span>
                </div>
              </div>
            </div>

            <!-- Core Parameters -->
            <div class="bg-white rounded-lg shadow-sm p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-4">核心参数</h3>
              <div class="grid grid-cols-2 gap-4">
                <div class="bg-gray-50 rounded-lg p-4">
                  <div class="text-sm text-gray-500 mb-1">环境温度</div>
                  <div class="text-xl font-bold text-gray-900">
                    {{ selectedVehicle.temperature }}℃
                    <span class="text-sm text-gray-500 font-normal">({{ selectedVehicle.thmVector[0] }})</span>
                  </div>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                  <div class="text-sm text-gray-500 mb-1">连续放电时长</div>
                  <div class="text-xl font-bold text-gray-900">
                    {{ selectedVehicle.dischargeTime }} 分钟
                    <span class="text-sm text-gray-500 font-normal">({{ selectedVehicle.thmVector[1] }})</span>
                  </div>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                  <div class="text-sm text-gray-500 mb-1">最大放电功率</div>
                  <div class="text-xl font-bold text-gray-900">
                    {{ selectedVehicle.maxPower }}kW
                    <span class="text-sm text-gray-500 font-normal">({{ selectedVehicle.thmVector[2] }})</span>
                  </div>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                  <div class="text-sm text-gray-500 mb-1">当前SOC</div>
                  <div class="text-xl font-bold text-gray-900">{{ selectedVehicle.soc }}%</div>
                </div>
              </div>

              <div class="mt-4 p-4 bg-blue-50 rounded-lg">
                <div class="text-sm text-gray-700 mb-2">当前热工况向量</div>
                <div class="text-lg font-bold text-blue-800">
                  THM = [{{ selectedVehicle.thmVector.join(', ') }}]
                </div>
                <el-button
                    type="text"
                    size="small"
                    class="mt-2"
                    @click="showNormalizationModal = true"
                >
                  查看归一化计算过程
                </el-button>
              </div>
            </div>

            <!-- Time Series Chart -->
            <div class="bg-white rounded-lg shadow-sm p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-4">时序趋势图</h3>
              <div class="h-64">
                <v-chart :option="chartOption" class="w-full h-full" />
              </div>
            </div>

            <!-- Actions -->
            <div class="bg-white rounded-lg shadow-sm p-6">
              <div class="flex space-x-4">
                <el-button
                    type="danger"
                    :class="{ 'animate-pulse': selectedVehicle.riskLevel === 'high' }"
                    @click="goToAnomalyDetection"
                >
                  查看异常工况分析
                </el-button>
                <el-button type="primary" @click="downloadData">
                  下载热工况数据
                </el-button>
              </div>
            </div>
          </div>

          <div v-else class="bg-white rounded-lg shadow-sm p-6">
            <div class="text-center text-gray-500 py-12">
              <el-icon size="48" class="mb-4"><Monitor /></el-icon>
              <p>请从左侧选择车辆查看详情</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Technical Modal -->
    <TechnicalModal
        v-model="showTechnicalModal"
        title="技术说明"
        :sections="technicalSections"
    />

    <!-- Normalization Modal -->
    <TechnicalModal
        v-model="showNormalizationModal"
        title="归一化计算过程"
        :sections="normalizationSections"
    />

    <!-- Vehicle Compare Modal -->
    <VehicleCompareModal
        v-model="showCompareModal"
    />

    <!-- Vehicle Table Modal -->
    <el-dialog v-model="showVehicleTable" title="车辆管理" width="90%" top="5vh">
      <VehicleTable />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import { QuestionFilled, Monitor } from '@element-plus/icons-vue'
import VehicleCard from '@/components/VehicleCard.vue'
import TechnicalModal from '@/components/TechnicalModal.vue'
import VehicleCompareModal from '@/components/VehicleCompareModal.vue'
import VehicleTable from '@/components/VehicleTable.vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
])

const router = useRouter()
const store = useAppStore()

const selectedRiskFilter = ref('all')
const selectedVehicle = ref(store.vehicles[0])
const lastRefreshTime = ref('2025-05-06 10:30:00')
const showTechnicalModal = ref(false)
const showNormalizationModal = ref(false)
const showCompareModal = ref(false)
const showVehicleTable = ref(false)
const expandedGroups = ref<string[]>(['高风险组', '中风险组', '低风险组'])
const checkAll = ref(false)

const filteredVehicles = computed(() => {
  if (selectedRiskFilter.value === 'all') {
    return store.vehicles
  }
  return store.vehicles.filter(v => v.riskLevel === selectedRiskFilter.value)
})

const isIndeterminate = computed(() => {
  const selectedCount = store.selectedVehicleCount
  return selectedCount > 0 && selectedCount < store.vehicles.length
})

const chartOption = computed(() => ({
  title: {
    text: 'SOC 和电流趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['SOC (%)', '电流 (A)'],
    bottom: 0
  },
  xAxis: {
    type: 'category',
    data: ['10:00', '10:05', '10:10', '10:15', '10:20', '10:25', '10:30']
  },
  yAxis: [
    {
      type: 'value',
      name: 'SOC (%)',
      position: 'left'
    },
    {
      type: 'value',
      name: '电流 (A)',
      position: 'right'
    }
  ],
  series: [
    {
      name: 'SOC (%)',
      type: 'line',
      data: [51.2, 49.8, 53.3, 52.1, 50.5, 49.2, 47.8],
      yAxisIndex: 0,
      itemStyle: { color: '#3b82f6' }
    },
    {
      name: '电流 (A)',
      type: 'line',
      data: [-10.2, -11.5, -11.8, -12.1, -12.0, -11.9, -12.3],
      yAxisIndex: 1,
      itemStyle: { color: '#ef4444' }
    }
  ]
}))

const technicalSections = [
  {
    title: '数据同步机制',
    content: '数据每 30 秒同步自 ev_status_data 表，用于构建热工况识别空间。系统自动监测车辆状态变化，及时识别异常工况。'
  },
  {
    title: '热工况向量构建',
    content: '通过环境温度、连续放电时长、最大放电功率三个维度构建热工况向量THM，各参数经过归一化处理便于分析。'
  },
  {
    title: '风险等级判定',
    content: '基于CTI（距离型临界热指标）初步判定风险等级：CTI < 0.01为高风险，0.01-0.05为风险预警，> 0.05为低风险。'
  }
]

const normalizationSections = computed(() => [
  {
    title: '温度归一化',
    content: `温度归一化：(${selectedVehicle.value?.temperature}-10)/(40-10)=${selectedVehicle.value?.thmVector[0]}`
  },
  {
    title: '放电时长归一化',
    content: `放电时长归一化：(${selectedVehicle.value?.dischargeTime}-0)/(60-0)=${selectedVehicle.value?.thmVector[1]}`
  },
  {
    title: '功率归一化',
    content: `功率归一化：(${selectedVehicle.value?.maxPower}-0)/(25-0)=${selectedVehicle.value?.thmVector[2]}`
  }
])

const toggleGroupExpand = (groupName: string) => {
  const index = expandedGroups.value.indexOf(groupName)
  if (index > -1) {
    expandedGroups.value.splice(index, 1)
  } else {
    expandedGroups.value.push(groupName)
  }
}

const handleCheckAllChange = (val: boolean) => {
  store.selectAllVehicles(val)
  checkAll.value = val
}

const batchAddToMonitor = () => {
  const selectedCount = store.selectedVehicleCount
  ElMessage.success(`已将 ${selectedCount} 辆车辆加入重点监控`)
}

const batchExportData = () => {
  const selectedVehicles = store.vehicles.filter(v => v.selected)
  const data = {
    exportTime: new Date().toISOString(),
    vehicles: selectedVehicles.map(v => ({
      id: v.id,
      model: v.model,
      fleet: v.fleet,
      soc: v.soc,
      temperature: v.temperature,
      thmVector: v.thmVector,
      riskLevel: v.riskLevel,
      lastUpdate: v.lastUpdate
    }))
  }

  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `batch_thermal_data_${new Date().toISOString().slice(0, 10)}.json`
  a.click()
  URL.revokeObjectURL(url)

  ElMessage.success(`已导出 ${selectedVehicles.length} 辆车辆的热工况数据`)
}

const selectVehicle = (vehicle: any) => {
  selectedVehicle.value = vehicle
  store.setCurrentVehicle(vehicle)
}

const goToAnomalyDetection = () => {
  store.setCurrentVehicle(selectedVehicle.value)
  router.push('/anomaly')
}

const downloadData = () => {
  // 模拟下载功能
  const data = {
    vehicleId: selectedVehicle.value?.id,
    thmVector: selectedVehicle.value?.thmVector,
    timestamp: new Date().toISOString()
  }

  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${selectedVehicle.value?.id}_thermal_data.json`
  a.click()
  URL.revokeObjectURL(url)
}

onMounted(() => {
  store.setCurrentVehicle(selectedVehicle.value)
  // 默认展开所有分组
  expandedGroups.value = Object.keys(store.groupedVehicles)
})
</script>